/**
 * 
 */
package com.sc.datacollect.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;

/**
 * @author dong
 *
 */
public class MongoDb {
	private static DB db_con = null;
	private static MongoClient mc = null;

	@SuppressWarnings("deprecation")
	public MongoDb(String host, int port, String dbname, String user, String password) {
		// 其他参数根据实际情况进行添加
		if (mc == null) {
			MongoClientOptions.Builder buide = new MongoClientOptions.Builder();
			buide.connectionsPerHost(100);// 与目标数据库可以建立的最大链接数
			buide.connectTimeout(1000 * 60 * 20);// 与数据库建立链接的超时时间
			buide.maxWaitTime(100 * 60 * 5);// 一个线程成功获取到一个可用数据库之前的最大等待时间
			buide.threadsAllowedToBlockForConnectionMultiplier(100);
			buide.socketKeepAlive(true);
			MongoClientOptions myOptions = buide.build();
			String[] host_list = host.split(",");
			List<ServerAddress> seeds = new ArrayList<ServerAddress>();
			for (String h : host_list) {
				ServerAddress sa = new ServerAddress(h, port);
				seeds.add(sa);

			}
			String mongoType = CommonConfig.mongoType;
			MongoCredential credential;
			if ("3".equals(mongoType)) {
				credential = MongoCredential.createScramSha1Credential(user, dbname, password.toCharArray());
			} else {
				credential = MongoCredential.createMongoCRCredential(user, dbname, password.toCharArray());
			}
			mc = new MongoClient(seeds, Arrays.asList(credential), myOptions);
			db_con = mc.getDB(dbname);
		}

	}

	/**
	 * 查询collection的记录数
	 * 
	 * @param qtable 查询的表
	 */
	public int count(String qtable) {
		int result = 0;
		DBCollection collection = db_con.getCollection(qtable);
		if (null != collection) {
			result = collection.find().count();
		}
		return result;
	}

	/**
	 * 按条件查询collection
	 * 
	 * @param qtable   查询的表
	 * @param qcolumns 查询的字段
	 * @param qquery   查询的条件
	 * @param qorder   排序
	 * @param qlimit   查询的记录数限制
	 */
	public List<DBObject> select(String qtable, DBObject qcolumns, DBObject qquery, DBObject qorder, int qlimit) {
		List<DBObject> result = null;
		DBCollection collection = db_con.getCollection(qtable);
		if (null != collection) {
			result = collection.find(qquery, qcolumns).sort(qorder).limit(qlimit).toArray();
		}
		return result;
	}

	public DBObject selectOne(String qtable, DBObject qcolumns, DBObject qquery) {
		DBObject result = null;
		DBCollection collection = db_con.getCollection(qtable);
		if (null != collection) {
			result = collection.findOne(qquery, qcolumns);
		}
		return result;
	}

	/**
	 * 插入数据到collection
	 * 
	 * @param qtable  插入数据的目标collection
	 * @param content 插入的数据
	 */
	public boolean insert(String qtable, DBObject content) {
		boolean result = false;
		WriteResult writeResult = null;
		DBCollection collection = db_con.getCollection(qtable);
		if (null != collection) {
			writeResult = collection.insert(content);
			if (null != writeResult) {
				if (writeResult.getN() > 0) {
					result = true;
				}
			}
		}
		return result;
	}

	public boolean insert(String qtable, String content) {
		boolean result = false;
		WriteResult writeResult = null;
		DBCollection collection = db_con.getCollection(qtable);
		DBObject conObject = (DBObject) com.mongodb.util.JSON.parse(content);
		if (null != collection) {
			writeResult = collection.save(conObject);
			if (null != writeResult) {
				if (writeResult.getN() > 0) {
					result = true;
				}
			}
		}
		return result;
	}

	public boolean insert(String qtable, List<String> conList) {
		boolean result = false;
		WriteResult writeResult = null;
		List<DBObject> conObjectList = new ArrayList<DBObject>();
		for (String conStr : conList) {
			DBObject conObject = (DBObject) com.mongodb.util.JSON.parse(conStr);
			conObjectList.add(conObject);
		}
		DBCollection collection = db_con.getCollection(qtable);
		if (null != collection) {
			writeResult = collection.insert(conObjectList);
			if (null != writeResult) {
				if (writeResult.getN() > 0) {
					result = true;
				}
			}
		}
		return result;
	}

	/**
	 * 按条件删除collection中的数据
	 * 
	 * @param qtable 要删除数据的集合(collection相当于表)
	 * @param qquery 删除条件
	 */
	public boolean delete(String qtable, DBObject qquery) {
		boolean result = false;
		WriteResult writeResult = null;
		DBCollection collection = db_con.getCollection(qtable);
		if (null != collection) {
			writeResult = collection.remove(qquery);
			if (null != writeResult) {
				if (writeResult.getN() > 0) {
					result = true;
				}
			}
		}
		return result;
	}

	/**
	 * 修改collection中的数据
	 * 
	 * @param qtable  要修改数据的集合(collection相当于表)
	 * @param qquery  修改条件
	 * @param qset    修改数据
	 * @param isnew   如果更新的数据不存在，是否添加一条新的
	 * @param ismulti 按条件是更新多条，还是第一条
	 */
	public boolean update(String qtable, DBObject qquery, DBObject qset, boolean isnew, boolean ismulti) {
		boolean result = false;
		WriteResult writeResult = null;
		DBCollection collection = db_con.getCollection(qtable);
		if (null != collection) {
			writeResult = collection.update(qquery, qset, isnew, ismulti);
			if (null != writeResult) {
				if (writeResult.getN() > 0) {
					result = true;
				}
			}
		}
		return result;
	}
}
